package com.gxa.common.interceptor;

import com.gxa.common.annotation.RequirePermission;
import com.gxa.common.util.JwtUtil;
import com.gxa.service.PermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 权限拦截器
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {
    
    private final JwtUtil jwtUtil;
    private final PermissionService permissionService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是方法处理器，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        
        // 检查是否有权限注解
        RequirePermission requirePermission = handlerMethod.getMethodAnnotation(RequirePermission.class);
        if (requirePermission == null) {
            // 没有权限注解，直接放行
            return true;
        }
        
        // 获取token - 优先从查询参数获取，然后从请求头获取
        String token = request.getParameter("token");
        if (token == null || token.trim().isEmpty()) {
            token = request.getHeader("token");
        }
        String authorization = request.getHeader("Authorization");
        
        // 如果token为空，尝试从Authorization头获取
        if ((token == null || token.trim().isEmpty()) && authorization != null && authorization.startsWith("Bearer ")) {
            token = authorization.substring(7); // 去掉"Bearer "前缀
        }
        
        if (token == null || token.trim().isEmpty()) {
            log.warn("请求缺少token: {}", request.getRequestURI());
            sendErrorResponse(response, 401, "未登录或token已过期");
            return false;
        }
        
        // 验证token
        if (!jwtUtil.validateToken(token)) {
            log.warn("token验证失败: {}", request.getRequestURI());
            sendErrorResponse(response, 401, "token无效或已过期");
            return false;
        }
        
        // 获取操作员等级
        Integer operatorLevel = jwtUtil.getOperatorLevelFromToken(token);
        if (operatorLevel == null) {
            log.warn("无法从token中获取操作员等级: {}", request.getRequestURI());
            sendErrorResponse(response, 401, "token信息不完整");
            return false;
        }
        
        // 检查权限
        String permissionName = requirePermission.value();
        if (!permissionService.hasPermission(operatorLevel, permissionName)) {
            log.warn("用户权限不足: operatorLevel={}, permission={}, uri={}", 
                    operatorLevel, permissionName, request.getRequestURI());
            sendErrorResponse(response, 403, "权限不足");
            return false;
        }
        
        log.info("权限验证通过: operatorLevel={}, permission={}, uri={}", 
                operatorLevel, permissionName, request.getRequestURI());
        return true;
    }
    
    /**
     * 发送错误响应
     */
    private void sendErrorResponse(HttpServletResponse response, int status, String message) throws IOException {
        response.setStatus(status);
        response.setContentType("application/json;charset=UTF-8");
        
        String jsonResponse = String.format(
                "{\"code\":%d,\"msg\":\"%s\",\"data\":null}", 
                status, message
        );
        
        try (PrintWriter writer = response.getWriter()) {
            writer.write(jsonResponse);
            writer.flush();
        }
    }
} 